#include "test.hpp"
#include <iostream>

test_info_holder::test_info_holder(void)
{

}

test_info_holder::~test_info_holder(void)
{
  free_test_info_table();
}

bool test_info_holder::load(std::string file_name)
{
  csv c ;
  std::ifstream file;
  file.open(file_name.c_str(), std::ios_base::in | std::ios_base::binary);
    if (!file.is_open())
      return  false;
  file.seekg(0, std::ios::end);
  int size = (int)file.tellg();
  file.seekg(0, std::ios::beg);

 // std::cout<<file.rdbuf()<<std::endl;

  int n_block = (size * 8 - 1) / AES_ENCRYPT_BLOCK_SIZE + 1;
  
  int len = n_block * AES_ENCRYPT_BLOCK_SIZE / 8;

  char* data = new char[len];
  if (!data)
    return false;
  memset(data, 0, len);

  file.read(data, size);

 /* char key[20];
  for (int i = 0; i < 20; i ++)
    key[i] = 123;

  aes_encrypt128 ae;
  ae.set_key(key, sizeof(key));
  ae.decrypt(data, data, n_block);*/

   std::string str(data);
  if (!c.load_from_string(str,'\t', true))
    return false;

  if (!build_test_info_table(c))
    return false;

  return true;

}

bool test_info_holder::build_test_info_table(csv& c)
{
  free_test_info_table();

  unsigned int row = c.get_row_num();

  for(unsigned int i = 0; i < row; i ++)
  {
    test_info*  arti = new test_info();
    if(!arti)
    {
      free_test_info_table();
      return false;
    }

    arti->id_ = c.get_int_value(i, column_id);
    arti->class_id_ = c.get_int_value(i, column_class_id);
    arti->modle_id_ = c.get_int_value(i, column_modle_id);
    arti->x_ = c.get_int_value(i, column_x);
    arti->y_ = c.get_int_value(i, column_y);
    arti->z_ = c.get_int_value(i, column_z);

    test_info_table_.insert(std::make_pair(arti->id_, arti));
  }

  return true;
}

void test_info_holder::free_test_info_table()
{
  test_info_holder_table::iterator it;
  for (it = test_info_table_.begin(); it != test_info_table_.end(); it ++)
  {
    delete (test_info*)it->second;
  }
  test_info_table_.clear();
}

test_info* test_info_holder::get_test_info_by_id(int id)
{
  test_info_holder_table::iterator it = test_info_table_.find(id);
  if (it == test_info_table_.end())
    return 0;
  return it->second;
}